package com.thread.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtil {

	// private static String host = "132.228.187.23";
	// private static String user = "was";
	// private static String password = "TYHJ_@5h4h#";
	private static String host = "192.168.1.203";
	private static String user = "yangjinlong";
	private static String password = "yanglong884";
	private static FTPClient ftpClient = null;

	/**
	 * 初始化
	 */
	public static boolean init() {
		ftpClient = new FTPClient();
		ftpClient.setControlEncoding("UTF-8");
		try {
			ftpClient.connect(host);
			ftpClient.login(user, password);
			int replyCode = ftpClient.getReplyCode();// 验证是否成功登陆服务器
			if (FTPReply.isPositiveCompletion(replyCode)) {
				System.out.println("连接成功");
				return true;
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 上传文件
	 * @param filePath 服务器地址路径
	 * @param fileName 服务器文件名称
	 * @param uploadFileName 要上传的文件地址（绝对路径）
	 */
	public static boolean upload(String filePath, String fileName, String uploadFileName) {
		boolean init = init();
		if (!init) {
			return false;
		}
		InputStream is = null;
		try {
			createFloder(filePath);
			is = new FileInputStream(new File(uploadFileName));
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			ftpClient.makeDirectory(filePath);
			ftpClient.changeWorkingDirectory(filePath);
			ftpClient.storeFile(fileName, is);
			is.close();

			System.out.println("上传成功");
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.logout();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * 下载文件
	 * @param servicePath 服务器文件路径
	 * @param ServiceFileName	服务器文件名称
	 * @param localPath	本地下载路径
	 * @return
	 */
	public static boolean download(String servicePath, String ServiceFileName, String localPath) {
		boolean init = init();
		if (!init) {
			return false;
		}
		OutputStream os = null;
		try {
			boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(servicePath);// 移动到服务器路径下
			if (changeWorkingDirectory) {
				// client通知service开放端口进行下载，每次数据连接都会开通一个端口来传输数据，linux出于安全限制，所以有些端口没有开放导致阻塞，获取不到文件列表
				ftpClient.enterLocalPassiveMode();
				FTPFile[] listFiles = ftpClient.listFiles("/IBM/ftpdata/tvasfile/vsopftp/unicast/803");
				for (FTPFile file : listFiles) {
					if (ServiceFileName.equalsIgnoreCase(file.getName())) {
						os = new FileOutputStream(new File(localPath + "/" + ServiceFileName));
						boolean retrieveFile = ftpClient.retrieveFile(ServiceFileName, os);
						if (retrieveFile) {
							System.out.println("下载文件成功");
						}
					}
				}
			} else {
				System.out.println("无此目录");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 创建多层文件夹
	 * @throws IOException 
	 */
	public static void createFloder(String remote) throws IOException {
		String directory = remote + "/";
		if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
			}
			end = directory.indexOf("/", start);
			String path = "";
			String paths = "";
			while (true) {
				String subDirectory = remote.substring(start, end);
				path = path + "/" + subDirectory;
				if (!existFile(path)) {
					boolean makeDirectory = makeDirectory(subDirectory);
					if (makeDirectory) {
						changeWorkingDirectory(subDirectory);
					} else {
						System.err.println("创建" + subDirectory + "目录失败");
					}
				} else {
					changeWorkingDirectory(subDirectory);
				}
				paths = paths + "/" + subDirectory;
				start = end + 1;
				end = directory.indexOf("/", start);
				if (end <= start) {
					break;
				}
			}
		}
	}

	// 创建文件夹
	public static boolean makeDirectory(String dir) {
		try {
			boolean makeDirectory = ftpClient.makeDirectory(dir);
			return makeDirectory;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	// 判断ftp服务器文件是否存在
	public static boolean existFile(String path) throws IOException {
		boolean flag = false;
		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		if (ftpFileArr.length > 0) {
			flag = true;
		}
		return flag;
	}

	// 改变目录路径
	public static boolean changeWorkingDirectory(String directory) {
		boolean flag = true;
		try {
			flag = ftpClient.changeWorkingDirectory(directory);
			if (flag) {
				System.out.println("进入文件夹" + directory + " 成功！");

			} else {
				System.out.println("进入文件夹" + directory + " 失败！开始创建文件夹");
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return flag;
	}

	/*public static void main(String[] args) throws IOException {
		// FtpUtil ftpUtil = new FtpUtil();
		// ftpUtil.init();
		// ftpUtil.createFloder("/test/yangjl/b");
		// new FtpUtil().upload("/test/yangjl/c", "install.log", "D:/install.log");
		// new FtpUtil().download("/test/yangjl/c", "install.log", "E:/");
		new FtpUtil().download("/IBM/ftpdata/tvasfile/vsopftp/unicast/803", "A-20180802-VSOPR711CZ1.TXT", "E:/");
	}*/
}
